var RULE_BOARD_ROWS;//棋盘行数
var RULE_BOARD_COLS;//棋盘列数
var RULE_CELL_SIZE = 60;//棋盘格子大小
var RULE_RED_RIVER;//红方河界
var RULE_BLACK_RIVER;//黑方河界
var RULE_RED_PALACE;//红方九宫格范围,以帅为起点,分别[右,上,左,下]的距离
var RULE_BLACK_PALACE;//黑方九宫格范围,以将为起点,分别[右,上,左,下]的距离
var RULE_LAYOUT_CONFIG;//棋盘布局
var RULE_PLAYERS = {//玩家列表
	"red":"红方",
	"black":"黑方"
};
var GAME_VALID;//记录游戏初始化的合法性
var GAME_BOARD_CLICK = false;//记录游戏的棋盘点击事件是否被初始化过
var DATA_CHESS;//记录所有棋子的状态
var DATA_CHESS_DEAD;//记录所有死亡棋子的状态
var DATA_CHESS_GRID;//记录所有有棋子的格子
var DATA_ACTION_HISTORY;//记录操作历史
var DATA_RED_PALACE;//记录红方九宫格坐标
var DATA_BLACK_PALACE;//记录黑方九宫格坐标
var DATA_CHESS_FREEZE;//记录冻结的棋子和操作次数
var DATA_PLAYERS;//记录当前操作玩家
var DATA_CURRENT_ROUND;//记录回合数
var DATA_CURRENT_PLAYER;//记录当前操作玩家
var DATA_CURRENT_PLAYER_INDEX;//记录当前操作玩家
var DATA_CURRENT_UNUSED_STEP;//记录未操作的次数
var DATA_CURRENT_SELECTED_CHESS;//记录当前选中的棋子
var DATA_CURRENT_SKILL;//记录当前选中的技能
var DATA_SKILL_USED_TIMES;//记录技能释放次数
// 监听DOM加载完成事件
document.addEventListener('DOMContentLoaded', function() {
	for (const layoutKey in LAYOUT_CONFIG) {
		let option = '<option value="'+layoutKey+'">'+layoutKey+'</option>';
		$("#layout").append(option);
	}
});
/**
 * 开始游戏
 */
function startGame() {
	GAME_VALID = true;
	
	DATA_CHESS = {};
	DATA_CHESS_DEAD = {};
	DATA_CHESS_GRID = {};
	DATA_ACTION_HISTORY = [];
	DATA_RED_PALACE = [];
	DATA_BLACK_PALACE = [];
	DATA_CHESS_FREEZE = {};
	DATA_PLAYERS = [];
	for (var playerCode in RULE_PLAYERS) {
		let playerName = RULE_PLAYERS[playerCode];
		DATA_PLAYERS.push(playerCode);
	}
	DATA_CURRENT_PLAYER = DATA_PLAYERS[0];
	DATA_CURRENT_PLAYER_INDEX = 0;
	DATA_CURRENT_ROUND = 1;
	DATA_CURRENT_UNUSED_STEP = 1;
	$("#gameDescription").text('当前回合：'+DATA_CURRENT_ROUND+"，请"+RULE_PLAYERS[DATA_CURRENT_PLAYER]+'操控棋子');
	DATA_CURRENT_SELECTED_CHESS = null;
	DATA_CURRENT_SKILL = null;
	DATA_SKILL_USED_TIMES = {};
	RULE_BOARD_ROWS = $("#rows").val() || 10;
	RULE_BOARD_COLS = $("#cols").val() || 10;
	RULE_RED_RIVER = $("#redRiver").val() || 4;
	RULE_BLACK_RIVER = $("#blackRiver").val() || 5;
	RULE_RED_PALACE = {
		"top": $("#redPalaceTop").val(),
		"bottom": $("#redPalaceBottom").val(),
		"left": $("#redPalaceLeft").val(),
		"right": $("#redPalaceRight").val()
	} || {
		"top": 2,
		"bottom": 0,
		"left": 1,
		"right": 1
	};
	RULE_BLACK_PALACE = {
		"top": $("#blackPalaceTop").val(),
		"bottom": $("#blackPalaceBottom").val(),
		"left": $("#blackPalaceLeft").val(),
		"right": $("#blackPalaceRight").val()
	} || {
		"top": 0,
		"bottom": -2,
		"left": 1,
		"right": 1
	};
	RULE_LAYOUT_CONFIG = $("#layout").val() || "默认";

	var board = document.getElementById('chessboard');
	$("#chessboard").empty();
	//渲染棋盘
	drawChessBoard(board);
	//渲染棋子
	drawChessLayout(board);
	//点击棋盘事件
	if (!GAME_BOARD_CLICK) {
		GAME_BOARD_CLICK = true;
		board.addEventListener('click', function (event) {
			const grid = getGridCoordinate(board, event);
			let selectedChess = DATA_CHESS_GRID[grid.x+","+grid.y];
			//如果选择了技能
			if (DATA_CURRENT_SKILL != null) {
				chessDoSkill(grid.x,grid.y);
			}
			//如果未选择技能
			else {
				// 点击棋子
				if (selectedChess != null) {
					//如果是自己的棋子
					if (selectedChess.piece.dataset.clan === DATA_CURRENT_PLAYER) {
						selectChess(selectedChess.piece.id);
					}
					//如果不是自己的棋子
					else {
						if (DATA_CURRENT_UNUSED_STEP === 0) {
							return;
						}
						chessDoCapture(selectedChess.piece.id,grid.x,grid.y);
					}
				}
				// 点击空白
				else {
					//如果当前未选择棋子
					if (DATA_CURRENT_SELECTED_CHESS == null) {
						//不管
					}
					//如果当前选择了棋子
					else {
						if (DATA_CURRENT_UNUSED_STEP === 0) {
							return;
						}
						chessDoMove(grid.x,grid.y);
					}
				}
			}
		});
	}
}
/**
 * 根据笛卡尔坐标的像素,获取对应坐标
 */
function getGridCoordinate(board,event) {
	// 获取棋盘元素的边界矩形信息（相对于视口）
	const boardRect = board.getBoundingClientRect();
	// 计算点击位置相对于棋盘左上角的像素偏移（视口坐标 - 棋盘左上角视口坐标）
	const relativeLeftFromTop = event.clientX - boardRect.left;
	const relativeTopFromTop = event.clientY - boardRect.top;
	// 转换为以左下角为原点的坐标：
	// - 横坐标left：与左上角为原点时相同（从左到右递增）
	// - 纵坐标top：棋盘高度 - 相对于左上角的纵向偏移（从下到上递增）
	const left = relativeLeftFromTop;
	const top = boardRect.height - relativeTopFromTop;
	// 处理边界情况（确保坐标在棋盘范围内）
	const clampedLeft = Math.max(0, Math.min(left, boardRect.width));
	const clampedTop = Math.max(0, Math.min(top, boardRect.height));
	// 计算网格横坐标（从左到右，0开始）
	// 使用Math.floor确保落在左侧的网格中
	const gridX = Math.floor(clampedLeft / RULE_CELL_SIZE);
	// 计算网格纵坐标（从下到上，0开始）
	// 同样使用Math.floor确保落在下方的网格中
	const gridY = Math.floor(clampedTop / RULE_CELL_SIZE);
	return {
		x: gridX,
		y: gridY
	};
}
/**
 * 选择棋子
 */
function selectChess(id) {
	//如果之前未选择棋子
	if (DATA_CURRENT_SELECTED_CHESS == null) {
		document.getElementById(id).classList.add("selected");
		DATA_CURRENT_SELECTED_CHESS = id;
	}
	//如果之前选过棋子
	else {
		//如果选的是同一个棋子
		if (DATA_CURRENT_SELECTED_CHESS === id) {
			document.getElementById(id).classList.remove("selected");
			DATA_CURRENT_SELECTED_CHESS = null;
		}
		//如果选的不是统一个棋子
		else {
			document.getElementById(DATA_CURRENT_SELECTED_CHESS).classList.remove("selected");
			document.getElementById(id).classList.add("selected");
			DATA_CURRENT_SELECTED_CHESS = id;
		}
	}
}
/**
 * 重置页面参数
 */
function resetConfig() {
	$("#rows").val(10);
	$("#cols").val(9);
	$("#redRiver").val(5);
	$("#blackRiver").val(5);
	$("#redPalaceTop").val(2);
	$("#redPalaceBottom").val(0);
	$("#redPalaceLeft").val(1);
	$("#redPalaceRight").val(1);
	$("#blackPalaceTop").val(0);
	$("#blackPalaceBottom").val(2);
	$("#blackPalaceLeft").val(1);
	$("#blackPalaceRight").val(1);
	$("#layout").val("默认");
	$("#firstMove").empty();
	let playerIndex = 0;
	for (let playerCode in RULE_PLAYERS) {
		let playerName = RULE_PLAYERS[playerCode];
		let option = '<option value="'+playerCode+'">'+playerName+'</option>';
		$("#firstMove").append(option);
		if (playerIndex === 0) {
			$("#firstMove").val(playerCode);
		}
		playerIndex++;
	}
}
/**
 * 完成操作
 */
function finishAction() {
	//冻结次数减1
	let freezeActionsInfo = {}
	for (let chessId in DATA_CHESS_FREEZE) {
		let freezeStep = DATA_CHESS_FREEZE[chessId];
		if (freezeStep > 1) {
			freezeStep = freezeStep - 1;
			freezeActionsInfo[chessId] = freezeStep;
		}
	}
	DATA_CHESS_FREEZE = freezeActionsInfo;
	//死亡次数加1
	let deadChessInfo = {}
	for (let chessId in DATA_CHESS_DEAD) {
		let deadStep = DATA_CHESS_DEAD[chessId];
		deadStep = deadStep + 1;
		deadChessInfo[chessId] = deadStep;
	}
	DATA_CHESS_DEAD = freezeActionsInfo;
	//清除当前选择技能
	DATA_CURRENT_SKILL = null;
	//清除当前选择棋子
	if (DATA_CURRENT_SELECTED_CHESS != null) {
		document.getElementById(DATA_CURRENT_SELECTED_CHESS).classList.remove("selected");
		DATA_CURRENT_SELECTED_CHESS = null;
	}
	//切换对手信息
	if (DATA_CURRENT_PLAYER_INDEX === DATA_PLAYERS.length - 1) {
		DATA_CURRENT_PLAYER_INDEX = 0;
		DATA_CURRENT_ROUND++;
	}
	else {
		DATA_CURRENT_PLAYER_INDEX++;
	}
	DATA_CURRENT_PLAYER = DATA_PLAYERS[DATA_CURRENT_PLAYER_INDEX];
	DATA_CURRENT_UNUSED_STEP = 1;
	$("#gameDescription").text('当前回合：'+DATA_CURRENT_ROUND+"，请"+RULE_PLAYERS[DATA_CURRENT_PLAYER]+'操控棋子');
}
